package com.lw.leetcode.arr.b;

import com.lw.test.util.Utils;

/**
 * Created with IntelliJ IDEA.
 * 6292. 子矩阵元素加 1
 *
 * @author liw
 * @version 1.0
 * @date 2023/1/15 15:55
 */
public class RangeAddQueries {

    public static void main(String[] args) {
        RangeAddQueries test = new RangeAddQueries();

        int n = 3;
        int[][] arr = {{1,1,2,2}, {0,0,1,1}};

        int[][] ints = test.rangeAddQueries(n, arr);
        Utils.toPrint(ints);
    }

    public int[][] rangeAddQueries(int n, int[][] queries) {
        int[][] arr = new int[n][n];
        for (int[] query : queries) {
            int a = query[0];
            int b = query[1];
            int c = query[2];
            int d = query[3];

            arr[c][d] += 1;
            if (a != 0 && b != 0) {
                arr[a - 1][b - 1] += 1;
            }
            if (b != 0) {
                arr[c][b - 1] -= 1;
            }
            if (a != 0) {
                arr[a - 1][d] -= 1;
            }

        }
        int[] ints = arr[n - 1];
        int[] items1 = new int[n];
        for (int i = n - 2; i >= 0; i--) {
            ints[i] += ints[i + 1];
        }
        System.arraycopy(ints, 0, items1, 0, n);
        int s = 0;
        for (int i = n - 2; i >= 0; i--) {
            ints = arr[i];
            s = ints[n - 1];
            ints[n - 1] += items1[n - 1] ;
            items1[n - 1] = ints[n - 1];
            for (int j = n - 2; j >= 0; j--) {
                int t = ints[j];
                s += t ;
                ints[j] = items1[j] + s;
                items1[j] += s;
            }
        }
        return arr;
    }

}
